package com.cole.miniapp.project.service.impl;

import com.cole.miniapp.common.exception.AuthorizationExtendException;
import com.cole.miniapp.common.service.RedisHashService;
import com.cole.miniapp.common.service.SessionAuthService;
import com.cole.miniapp.project.domain.FcmUser;
import com.cole.miniapp.project.service.UserService;
import com.cole.miniapp.project.vo.SessionInfoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SessionAuthServiceImpl implements SessionAuthService {

	@Autowired
	@Qualifier("redisSessionServiceByHash")
	RedisHashService<String, SessionInfoEntity> sessionService;

	@Autowired
	UserService userService;

	@Override
	public Object auth(String token, String userId) {
		SessionInfoEntity sessionInfoEntity = sessionService.get(userId);
		if (sessionInfoEntity==null){
			return null;
		}
		Date current=new Date();
		long time=current.getTime()-sessionInfoEntity.getCreatetime().getTime();
		int outTime=2*60*60*1000;
		if (time>outTime){
			throw new AuthorizationExtendException();
		}
		if (!token.equals(sessionInfoEntity.getLoginToken())) {
			throw new AuthorizationExtendException();
		}
		FcmUser fcmUser= userService.getUserById(Long.valueOf(userId));
		return fcmUser;
	}

}
